// 2025/11/13
// 从中序与后序遍历构造二叉树

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    typedef vector<int>::iterator iitor;

    TreeNode* helper(iitor& it, iitor left, iitor right)
    {
        if(left > right)
            return nullptr;
        TreeNode* root = new TreeNode(*it);
        iitor mid = left;
        while(mid <= right && *mid != *it)
            mid++;
        it--;
        root->right = helper(it, mid + 1, right);
        root->left = helper(it, left, mid - 1);
        return root;
    }

    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        auto it = --postorder.end();
        return helper(it, inorder.begin(), --inorder.end());
    }
};